# coding:utf8
import copy

from appserver import db_store
from sqlalchemy import or_
from models.entity.district_with_facility import DistrictWithFacility
from models.entity.model_base import ModelBase

"""
模块数据模型
"""
"""不要改了"""

# 设施
class Facility(ModelBase):
    __tablename__ = "facility"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'设施名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"设施编码")
    description = db_store.Column(db_store.String(255), nullable=False, comment=u"描述")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序", default=0)
    status = db_store.Column(db_store.Integer, comment=u"当前状态", default=0)  # 0正常 1 异常 2弃用
    facility_type = db_store.Column(db_store.Integer, db_store.ForeignKey('facility_type.id'), nullable=False,
                                     comment=u"设施分类ID")
    lat=db_store.Column(db_store.Float, comment=u"经度")
    lng= db_store.Column(db_store.Float, comment=u"纬度")
    program = db_store.Column(db_store.String(255), comment=u"项目")
    icon = db_store.Column(db_store.String(32), comment=u"图标")

    def __repr__(self):
        return "<Facility %.2f>" % self.id

    def to_dict(self):
        rdic={}
        rdic["data_type"]=2
        rdic["id"]=self.id
        rdic["name"]=self.name
        rdic["code"]=self.code
        rdic["description"]=self.description
        rdic["dis_order"]=self.dis_order
        rdic["status"]=self.status
        rdic["facility_type"]=self.facility_type
        rdic["lat"]=self.lat
        rdic["lng"]=self.lng
        rdic["program"]=self.program
        rdic["icon"]=self.icon
        connector=DistrictWithFacility.query.filter_by(facility_id=self.id).first()
        if connector is not None:
            rdic["district_id"]=connector.district_id
        else:
            rdic["district_id"]=None
        return rdic

    ### 我加的方法
    def from_dict(self, rev_source):
        source = copy.deepcopy(rev_source)
        print('source', source)
        # if "parent_id" in source:
        #     source["parent_id"] = source.pop("parent_id")
        # if "level" in source:
        #     source["depth"] = source.pop("level")
        # if "children" in source:
        #     source.pop("children")
        # ******因为facility模型中没有district_id这个字段所以要pop掉
        if "district_id" in source:
            source.pop('district_id')
        for k in source:
            print('k',k)
            try:
                getattr(self, k)
                print('getattr',getattr(self, k))
            except AttributeError as e:
                print(e)
                raise RuntimeError("数据格式错误")
            setattr(self, k, source[k])
            # print('setattr',setattr(self, k, source[k]))

    @staticmethod
    def get_facility_by_id(id):
        return Facility.query.filter_by(id=id).first()

    @staticmethod
    def get_facility_by_name(name):
        return Facility.query.filter_by(name=name).first()

    @staticmethod
    def get_facility_by_code(code):
        return Facility.query.filter_by(code=code).first()

    @staticmethod
    def get_facilities_by_facility_type_id(type_id):
        return Facility.query.filter_by(facility_type=type_id).all()
    
    @staticmethod
    def get_facilities_by_district_id(district_id):
        # 通过第三张表的分区id查询到所有的设施,然后遍历,取出设施id,然后用设施表查出所以设施
        connectors=DistrictWithFacility.query.filter_by(district_id=district_id).all()
        print('connectors', connectors)
        rlist=[]
        for item in connectors:
            rlist.append(Facility.query.filter_by(id=item.facility_id).first())
        return rlist

    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        facilities = Facility.query.filter(
            or_(Facility.code.like('%' + query_word + '%'), Facility.name.like('%' + query_word + '%'),
                Facility.description.like('%' + query_word + '%'))).all()
        for obj in facilities:
            data.append(obj.to_dict())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp